from redis import Redis

"""连接redis"""
#方式1
# rconn = Redis.from_url('redis://127.0.0.1:6379/0')

# 方式2:
# rconn  =Redis(host='IP地址',port=端口,db=数据库ID,username=用户名,password=密码,charset="utf-8")
rconn  =Redis(host='127.0.0.1',port=6379,db=0,charset="utf-8")
print(rconn)

"""操作key"""
ret = rconn.keys("*")
print(ret)

"""操作字符串"""
# 设置一个有效期的字符串数据
# setex key second value
rconn.setex('sms_13213613096',5*60,'22233')

#获取一个字符串[bytes类型]
ret = rconn.get('sms_13213613096')
print(ret.decode())


"""操作哈希[字典]"""
# 给哈希添加/设置单个键值对
rconn.hset('user:10','username','xiaohong')
# 给哈希添加/更新多个键值对
user_11={
    'username':"小白",
    'age':16,
    'sex':0
}
rconn.hset('user:11',mapping=user_11)

# 获取字典所有成员，字典的所有成员都是键值对，而键值对也是bytes类型，所以需要推导式进行转换
ret = rconn.hgetall("user:11")
for key,value in ret.items():
    print(key.decode(),value.decode())